package com.emm.yixun.marketing.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.jws.WebService;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.RoomChangeHistoryService;
import com.emm.yixun.basic.service.SellControlService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.annotation.Constants;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.SellControl;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.ProjectRoomDto;
import com.emm.yixun.common.model.dto.RetainDetailView;
import com.emm.yixun.common.model.dto.RoomChangeHistoryDto;
import com.emm.yixun.common.model.dto.SellControlDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.marketing.service.RetainServiceFacade;
import com.emm.yixun.marketing.service.SellControlServiceFacade;

@Service("sellControlServiceFacade")
@WebService(name = "com.emm.yixun.marketing.service.SellControlServiceFacade")
public class SellControlServiceFacadeImpl implements SellControlServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SellControlService service;
	@Autowired
	private ProjectRoomService projectRoomService;
	
	@Autowired
	private RoomChangeHistoryService roomChangeHistoryService;
	
	@Autowired
	RetainServiceFacade retainServiceFacade;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private DataPermissionService dataPermissionService;

	@Override
	public Response<SellControlDto> save(SellControlDto dto,User user) {
		Response<SellControlDto> response = new Response<SellControlDto>();
		try {
			//roomId: 单一销控
			//roomIds: 批量销控
			if(null != dto.getRoomId()){
				//roomId不为空,为单个销控,将房源Id存入ids
				dto.setRoomIds(String.valueOf(dto.getRoomId()));
			}
			String[] roomIdsArr = dto.getRoomIds().split("[,]");
			for(int ii=0; ii<roomIdsArr.length; ii++){
				long roomId = Long.parseLong(roomIdsArr[ii]);
				ProjectRoom room = projectRoomService.selectById(roomId);
				if(room.getRoomStatus().equals(RoomStatusEnum.MA.getNo())){
					continue;
				}
				dto.setRoomId(roomId);
				dto.setAgentId(user.getId());
				dto.setControlDate(Calendar.getInstance().getTime());
				dto.setMerchantId(user.getMerchantId());
				dto.setAccessCode(room.getProjectCode());
				dto.setUserCode(user.getUserCode());
				dto.setCreateUserId(user.getId());
				dto.setCreateTime(new Date());
				dto.setDelFlag("0");
				dto.setUpdateTime(new Date());
				SellControlDto mDto = service.create(dto);
				if (null == mDto) {
					response.fail("80000", "保存数据错误");
					return response;
				}else{
					//新增房间的变更记录
					RoomChangeHistoryDto hisdto = new RoomChangeHistoryDto();
					hisdto.setRoomId(roomId);
					hisdto.setBusinessDynamics(RoomStatusEnum.MA.getDes());
					hisdto.setRemark("房态由【"+RoomStatusEnum.getByNo(room.getRoomStatus()).getDes()+"】转为【"+RoomStatusEnum.MA.getDes()+"】");
					hisdto.setMerchantId(user.getMerchantId());
					hisdto.setAccessCode(room.getProjectCode());
					hisdto.setUserCode(user.getUserCode());
					hisdto.setCreateUserId(user.getId());
					hisdto.setCreateTime(new Date());
					hisdto.setDelFlag("0");
					hisdto.setBusinessHref("/marketing/sellControl/sellDetail?id="+mDto.getId());
					roomChangeHistoryService.create(hisdto);
					//更改房间状态为销控
					ProjectRoomDto roomEntity = new ProjectRoomDto();
					roomEntity.setId(room.getId());
					roomEntity.setRoomStatus(RoomStatusEnum.MA.getNo());
					projectRoomService.update(roomEntity);
				}
			}
			response.success();
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}
	@Override
	public Response<Integer> updateByPrimaryKey(SellControlDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			SellControlDto mDto = new SellControlDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<SellControl> findById(Long id) {
		Response<SellControl> response = new Response<SellControl>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			SellControl entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<SellControl> findByDto(SellControlDto dto) {
		ResponseList<SellControl> response = new ResponseList<SellControl>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<SellControl> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<SellControl> findPageByDto(SellControlDto dto, Integer begin, Integer row) {
		Page<SellControl> response = new Page<SellControl>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<SellControl> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.emm.yixun.marketing.service.SellControlServiceFacade#getSellControlDtoList(com.emm.yixun.common.model.dto
	 * .SellControlDto, java.lang.Integer, java.lang.Integer)
	 */
	@Override
	public Response<Page<SellControlDto>> getSellControlDtoList(SellControlDto reqDto, Integer pageSize, Integer pageNum) {
		Response<Page<SellControlDto>> resDto = new Response<Page<SellControlDto>>();
		try {
			//数据权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(reqDto.getPermissionUserId(), reqDto.getResourcesCode(), reqDto.getPrefix(), reqDto.getColumnName());
				String [] dataPermissionArr = dataPermission.split(":");
				if("00".equals(dataPermissionArr[0])){
					resDto.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					resDto.setSuccess(false);
					return resDto;
				}
				reqDto.setDataPermission(dataPermissionArr[1]);
			}
			Page<SellControlDto> page = service.getPageDtoModel(reqDto, PageUtil.begin(pageNum, pageSize), pageSize);
			page.setPageSize(pageSize);
			resDto.setSuccess(true);
			resDto.setEntity(page);
			return resDto;
		} catch (Exception e) {
			logger.error("查询分页数据错误：{}", e);
			resDto.setSuccess(false);
			return resDto;
		}
	}
	@Override
	public RetainDetailView getSellDetail(Long id) {
		RetainDetailView rdv = new RetainDetailView();
		try {
			SellControl sellControl = service.selectById(id);
			if(sellControl != null){
				rdv=BeanUtil.convert2T(rdv, sellControl);
				User user = userService.selectById(rdv.getAgentId());
				rdv.setAgentCN(user.getUserName());
				rdv=retainServiceFacade.getProjectRoomInfo(rdv, sellControl.getRoomId());
				
				User updateName = userService.selectById(sellControl.getUpdateUserId());
				if(updateName != null){
					rdv.setUpdateUser(updateName.getUserName());
					rdv.setUpdateDate(sellControl.getUpdateTime());
					rdv.setRemark(sellControl.getRemark());
				}
			}
			return rdv;
		} catch (Exception e) {
			logger.error("getSellDetail error: ", e);
		}
		return null;
	}
	@Override
	public Response<Boolean> sellControlRevoke(Long id,User user,String remark) {
		Response<Boolean> response = new Response<Boolean>();
		try {
			revoke(id, user, remark);
			response.setEntity(true);
			return response;
		} catch (Exception e) {
			logger.error("sellControlRevoke error: ", e);
		}
		return null;
	}
	
	/**
	 * 批量撤销销控
	 */
	@Override
	public Response<Boolean> batchSellControlRevoke(String ids,User user,String remark) {
		Response<Boolean> response = new Response<Boolean>();
		try {
			batchRevoke(ids, user, remark);
			response.setEntity(true);
			return response;
		} catch (Exception e) {
			logger.error("batchSellControlRevoke error: ", e);
		}
		return null;
	}
	
	
	public void revoke(Long id,User user,String remark){
		SellControl control = service.selectById(id);
		ProjectRoom room = projectRoomService.selectById(control.getRoomId());
		SellControlDto controlDto = new SellControlDto();
		controlDto.setId(id);
		controlDto.setControlType("1");
		controlDto.setRemark(remark);
		controlDto.setUpdateUserId(user.getId());
		service.update(controlDto);
		//新增变更记录
		RoomChangeHistoryDto hisdto = new RoomChangeHistoryDto();
		hisdto.setRoomId(control.getRoomId());
		hisdto.setBusinessDynamics("撤销"+RoomStatusEnum.MA.getDes());
		hisdto.setRemark("房态由【"+RoomStatusEnum.getByNo(room.getRoomStatus()).getDes()+"】转为【"+RoomStatusEnum.VENDIBILITY.getDes()+"】");
		hisdto.setMerchantId(user.getMerchantId());
		hisdto.setAccessCode(room.getProjectCode());
		hisdto.setUserCode(user.getUserCode());
		hisdto.setCreateUserId(user.getId());
		hisdto.setCreateTime(new Date());
		hisdto.setDelFlag("0");
		hisdto.setBusinessHref("/marketing/sellControl/sellDetail?id="+controlDto.getId());
		roomChangeHistoryService.create(hisdto);
		//更改房间状态
		ProjectRoomDto roomEntity = new ProjectRoomDto();
		roomEntity.setId(room.getId());
		roomEntity.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());
		projectRoomService.update(roomEntity);
	}
	
	public void batchRevoke(String ids,User user,String remark){
		String idsArr[] = ids.split("[,]");
		for(int ii=0; ii<idsArr.length; ii++){
			if(StringUtils.isNotEmpty(idsArr[ii])){
				long roomId = Long.valueOf(idsArr[ii]);
				SellControlDto sellControlDto = new SellControlDto();
				sellControlDto.setRoomId(roomId);
				sellControlDto.setControlType("0");
				SellControl control = service.selectByDto(sellControlDto);
				if(null != control){
					ProjectRoom room = projectRoomService.selectById(control.getRoomId());
					if(room.getRoomStatus().equals(RoomStatusEnum.VENDIBILITY.getNo())){
						continue;
					}
					sellControlDto = new SellControlDto();
					sellControlDto.setId(control.getId());
					sellControlDto.setControlType("1");
					sellControlDto.setRemark(remark);
					sellControlDto.setUpdateUserId(user.getId());
					service.update(sellControlDto);
					//新增变更记录
					RoomChangeHistoryDto hisdto = new RoomChangeHistoryDto();
					hisdto.setRoomId(control.getRoomId());
					hisdto.setBusinessDynamics("撤销"+RoomStatusEnum.MA.getDes());
					hisdto.setRemark("房态由【"+RoomStatusEnum.getByNo(room.getRoomStatus()).getDes()+"】转为【"+RoomStatusEnum.VENDIBILITY.getDes()+"】");
					hisdto.setMerchantId(user.getMerchantId());
					hisdto.setAccessCode(room.getProjectCode());
					hisdto.setUserCode(user.getUserCode());
					hisdto.setCreateUserId(user.getId());
					hisdto.setCreateTime(new Date());
					hisdto.setDelFlag("0");
					hisdto.setBusinessHref("/marketing/sellControl/sellDetail?id="+sellControlDto.getId());
					roomChangeHistoryService.create(hisdto);
					//更改房间状态
					ProjectRoomDto roomEntity = new ProjectRoomDto();
					roomEntity.setId(room.getId());
					roomEntity.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());
					projectRoomService.update(roomEntity);
				}
			}
		}
	}
	
	@Override
	public void taskRun() {
		try {
			List<SellControl> sellList = service.selectSellByEndValidity();
			if(sellList!=null&&sellList.size()>0){
				for (SellControl sell:sellList) {
					
					UserDto dto = new UserDto();
					dto.setMerchantId(sell.getMerchantId());
					dto.setIsAdmin("1");
					List<User> user = userService.selectListByDto(dto);
					if(user!=null&&user.size()>0){
						revoke(sell.getId(), user.get(0), Constants.MSG);
					}
					
				}
			}
		} catch (Exception e) {
			logger.error("taskRun error: ", e);
		}
	}
}
